package com.shine.app.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.shine.app.R;
import com.shine.app.bean.PlaceBean;
import com.shine.app.bean.PlaceNearBean;
import com.shine.app.commons.Convert;
import com.shine.app.commons.StringUtils;

public class LocationAdapter extends BaseAdapter {
	private List<PlaceNearBean> data;
	private LayoutInflater inflater;

	static class ViewHolder {
		private TextView nameTextView;
		private TextView addressTextView;
		private TextView distanceTextView;
		private TextView idTextView;
	}

	public LocationAdapter() {

	}

	public LocationAdapter(Context context, List<PlaceNearBean> list) {
		this.inflater = LayoutInflater.from(context);
		this.data = list;
	}

	public List<PlaceNearBean> getData() {
		return data;
	}

	public void setData(List<PlaceNearBean> data) {
		this.data = data;
	}

	public int getCount() {
		return data.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.location_item, null);
			viewHolder = new ViewHolder();
			viewHolder.nameTextView = (TextView) convertView
					.findViewById(R.id.name);
			viewHolder.idTextView = (TextView) convertView
					.findViewById(R.id.id);
			viewHolder.addressTextView = (TextView) convertView
					.findViewById(R.id.address);
			viewHolder.distanceTextView = (TextView) convertView
					.findViewById(R.id.distance);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		PlaceNearBean bean = data.get(position);
		PlaceBean placeBean = bean.getLocation();
		viewHolder.idTextView.setTag(bean);
		viewHolder.nameTextView.setText(placeBean.getFullName());
		String address = getAddress(placeBean);
		viewHolder.addressTextView.setText(address);
		if (StringUtils.isEmpty(address)) {
			viewHolder.addressTextView.setVisibility(View.GONE);
		} else {
			viewHolder.addressTextView.setVisibility(View.VISIBLE);
		}
		viewHolder.idTextView.setText(String.valueOf(placeBean.getId()));
		double distance = Convert.getConvert().converDouble(bean.getDistance());
		viewHolder.distanceTextView
				.setText(String.valueOf(distance) + " miles");
		return convertView;
	}

	private String getAddress(PlaceBean placeBean) {
		String address = "";
		String city = placeBean.getCity();
		if (StringUtils.isEmpty(city)) {
			address = placeBean.getStateCode();
		} else {
			address = city + ", " + placeBean.getStateCode();
		}
		return address;
	}

}
